package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Types;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CodeBuilder {
	public static HashMap<String,String> config;
	/**
	 * 创建部分代码，根据选择的创建类型{@link BuildType},老创建不同的代码
	 * 根据填写的主表名，依赖主表名来创建代码，其他表都是依附该主表
	 * @param tables 需要创建的表集合
	 * @param type 需要创建的类型
	 * @param mainTable 需要创建的表集合
	 * @return
	 */
	public boolean build(List<String> tables,BuildType type,String mainTable) {
		tables.forEach(i->{
			buildByTable(i,type,mainTable);
		});
		return true;
	}
	/**
	 * 创建所有
	 * @return
	 */
	public boolean buildAll() {
		return build(DataSourceInfoUtil.getTables(),null,null);
	}
	
	private boolean buildByTable(String tableName,BuildType type, String mainTable) {
		//获取表的注释
		String tableComment=DataSourceInfoUtil.getAllTableComment().get(tableName);
		//获取字段以及字段的注释
		List<Map<String, Object>> tableInfo=DataSourceInfoUtil.getTabelInfo(tableName);
		//创建bean文件
//		return buildBeanFile(tableName,tableComment,tableInfo,type,mainTable);
		//创建core文件
//		return buildCoreFile(tableName,tableComment,tableInfo);
		//创建handler文件
//		return buildHandlerFile(tableName,tableComment,tableInfo, type);
		//创建jsp文件
//		return buildJspFile(tableName,tableComment,tableInfo, type);
		boolean onlyHandlerFile=Utils.isEmpty(config.get("OnlyHandlerFile"));
		boolean onlyCoreFile=Utils.isEmpty(config.get("OnlyCoreFile"));
		boolean onlyJspFile=Utils.isEmpty(config.get("OnlyJspFile"));
		boolean resultHandler=true;
		boolean resultCore=true;
		boolean resultJsp=true;
        if(!onlyHandlerFile) resultHandler=buildHandlerFile(tableName,tableComment,tableInfo,type);
        if(!onlyCoreFile) resultCore=buildCoreFile(tableName,tableComment,tableInfo);
        if(!onlyJspFile)resultJsp=buildJspFile(tableName,tableComment,tableInfo,type);
        if(onlyHandlerFile&&onlyCoreFile&&onlyJspFile)
		return buildCoreFile(tableName,tableComment,tableInfo)
				&&buildHandlerFile(tableName,tableComment,tableInfo,type)
				&&buildJspFile(tableName,tableComment,tableInfo,type);
        return resultHandler&&resultCore&&resultJsp;
	}
	//创建jsp文件
	private boolean buildJspFile(String tableName,String tableComment, List<Map<String, Object>> tableInfo, BuildType type) {
		//如果在目录当中已经有表名一样的目录，那么就放在该目录下面
		String fileUrl=getFileUrl(config.get("ProjectUrl")+config.get("FrontEndUrl"),tableName);
		//获取表注释  如果表注释最后一个字有表字那么去除这个字
		tableComment=getTableComment(tableName);
		String javaClassName=getJavaClassName(tableName);
		String jspName=tableName.substring(4);
		StringBuffer stringBuffer = new StringBuffer();
		//拼接jsp 导包部分和top部分
		appendJspImportPackageAndTop(stringBuffer, jspName, javaClassName);
		//拼接jsp html头和样式部分
		appendJspHtmLHeadAndStype(stringBuffer);
	    //拼接jsp js部分
		appendJspJs(stringBuffer,javaClassName,tableName,tableInfo,tableComment);
		//拼接jsp body部分
		appendJspBody(stringBuffer, tableComment, javaClassName, tableInfo);;
		return buildTargetFile(stringBuffer.toString(),fileUrl+jspName+"","jsp");
	}

	//创建handler文件
	private boolean buildHandlerFile(String tableName,String tableComment, List<Map<String, Object>> tableInfo, BuildType type) {
		//如果在目录当中已经有表名一样的目录，那么就放在该目录下面
		String fileUrl=getFileUrl(config.get("ProjectUrl")+config.get("HandlerUrl"),tableName);
		
		//获取表注释  如果表注释最后一个字有表字那么去除这个字
		tableComment=getTableComment(tableName);
		
		String javaClassName=getJavaClassName(tableName);
		String urlPageName=tableName.substring(4).toUpperCase();
		// 获取文件下的定义的包名
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("package ").append(getPackName(fileUrl) + ";").append("\r\n\n");
		
		stringBuffer.append("" + 
				"\r\n" + 
				"import java.io.IOException;\r\n" + 
				"import java.util.List;\r\n" + 
				"import javax.servlet.ServletContext;\r\n" + 
				"import javax.servlet.ServletException;\r\n" + 
				"import javax.servlet.http.HttpServletRequest;\r\n" + 
				"import javax.servlet.http.HttpServletResponse;\r\n" + 
				"import javax.servlet.http.HttpSession;\r\n" + 
				"import org.apache.log4j.Logger;\r\n" + 
				"import com.corget.util.CommonUtil;\r\n" + 
				"import com.corget.util.CommonUtil.DataSourceType;\r\n" + 
				"import ptt.Constant;\r\n" + 
				"import ptt.server.webserver;\r\n" + 
				"\r\n" + 
				"/**\r\n" + 
				" * "+tableComment+"Handler类 \r\n" + 
				" * @author "+config.get("ProgramName")+"\r\n" +
				" * @version "+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"\r\n" +
				" */\r\n"+
				"public class "+javaClassName+"Handler"+" extends EventHandlerBase {\r\n" + 
				"\r\n" + 
				"	private static Logger logger = Logger.getLogger("+javaClassName+"Handler"+".class);\r\n" + 
				"\r\n" + 
				"	@Override\r\n" + 
				"	public void process(ServletContext sc, HttpServletRequest request, HttpServletResponse response)\r\n" + 
				"			throws IOException, ServletException {\r\n" + 
				"\r\n" + 
				"		HttpSession session = request.getSession();\r\n" + 
				"		Integer orgId = (Integer) session.getAttribute(Constant.ORG_ID);\r\n" + 
				"		if (orgId == null) {\r\n" + 
				"			logger.debug(\"add a user failed for can't find org data!\");\r\n" + 
				"			throw new IOException(\"can't find your org data.\");\r\n" + 
				"		}\r\n" + 
				"		// 校验是否重复请求 校验是否有权限\r\n" + 
				"		if (!CommonUtil.checkRepetitiveOperation(request, response)\r\n" + 
				"				&& !webserver.checkOrgPrivilege(request, response, Constant.Privilege_Org_EditDepartment))\r\n" + 
				"			return;\r\n" + 
				"		// 获取操作核心参数\r\n" + 
				"		String operation = request.getParameter(Constant.OPERATION);\r\n" + 
				"		// 通过参数处理不同的请求\r\n" + 
				"		if (operation != null) {\r\n" + 
				"			if (!Dispatch.valueOf(operation.toUpperCase()).dispatch(request, response)) {\r\n" + 
				"				forword(RequestURL.URL_"+urlPageName+", request, response);\r\n" + 
				"				return;\r\n" + 
				"			}\r\n" + 
				"		}\r\n" + 
				"		forword(RequestURL.URL_"+urlPageName+", request, response);\r\n" + 
				"	}\r\n" + 
				"\r\n");
		stringBuffer.append(
				"	/**\r\n" + 
				"	 * 业务处理类\r\n" + 
				"	 * \r\n" + 
				"	 * @author corget\r\n" + 
				"	 */\r\n" + 
				"	private enum Dispatch {\r\n");
		if(!config.containsKey("NoOperatingArea"))
		stringBuffer.append("		// 修改操作\r\n" + 
				"		UPDATE"+javaClassName+"DATA() {\r\n" + 
				"			@Override\r\n" + 
				"			public boolean dispatch(HttpServletRequest request, HttpServletResponse response) {\r\n" + 
				"				return false;\r\n" + 
				"			}\r\n" + 
				"		},\r\n" + 
				"		// 增加\r\n" + 
				"		INSERT"+javaClassName+"DATA() {\r\n" + 
				"			@Override\r\n" + 
				"			public boolean dispatch(HttpServletRequest request, HttpServletResponse response) {\r\n" + 
				"				return false;\r\n" + 
				"			}\r\n" + 
				"		},\r\n" + 
				"		// 删除\r\n" + 
				"		DELETE"+javaClassName+"DATA() {\r\n" + 
				"			@Override\r\n" + 
				"			public boolean dispatch(HttpServletRequest request, HttpServletResponse response) {\r\n" + 
				"				return false;\r\n" + 
				"			}\r\n" + 
				"		};\r\n");
		stringBuffer.append("		// 数据查找操作\r\n" + 
				"		LIST"+javaClassName+"DATA() {\r\n" + 
				"			@Override\r\n" + 
				"			public boolean dispatch(HttpServletRequest request, HttpServletResponse response) {\r\n" +
				"				return false;\r\n" + 
				"			}\r\n" + 
				"		};\r\n"+
				"		public abstract boolean dispatch(HttpServletRequest request, HttpServletResponse response);\r\n" + 
				"	}\r\n");
		if(!config.containsKey("NoOperatingArea"))
		stringBuffer.append("	// 增加记录\r\n" + 
				"	private boolean insert"+javaClassName+"Data(List<String> param) {\r\n" + 
				"		String sqlInsert =\""+getInsertSql(tableName, tableInfo)+"\";\r\n" + 
				"		return CommonUtil.insert(sqlInsert, param, DataSourceType.MANA);\r\n" + 
				"	}\r\n" + 
				"\r\n" + 
				"	// 修改数据\r\n" + 
				"	private boolean update"+javaClassName+"Data(List<Object> param) {\r\n" + 
				"		String sqlUpdate = \""+getUpdateSql(tableName, tableInfo)+"\";\r\n" + 
				"		return CommonUtil.update(sqlUpdate, param, DataSourceType.MANA);\r\n" + 
				"	}\r\n" + 
				"\r\n" + 
				"	// 删除数据\r\n" + 
				"	private boolean delete"+javaClassName+"Data(List<String> param) {\r\n" + 
				"		String sqlDelete =\""+getDeleteSql(tableName)+"\";\r\n" + 
				"		return CommonUtil.delete(sqlDelete, param, DataSourceType.MANA);\r\n" + 
				"	}\r\n" + 
				"\r\n" + 
				"	// 是否存在\r\n" + 
				"	private boolean get"+javaClassName+"ById(List<Object> param) {\r\n" + 
				"		String sqlQuery = \""+getSimpleQuerySql(tableName)+"\";\r\n" + 
				"		return CommonUtil.querySimple(sqlQuery, param, DataSourceType.MANA);\r\n" + 
				"	}\r\n" + 
				"\r\n");
		appendQueryCode(stringBuffer);
		stringBuffer.append("\r\n" + 
				"}\r\n" + 
				"//");
		return buildTargetFile(stringBuffer.toString(),fileUrl+javaClassName+"Handler","java");
	}

	//创建core文件
	private boolean buildCoreFile(String tableName,String tableComment, List<Map<String, Object>> tableInfo) {
		//如果在目录当中已经有表名一样的目录，那么就放在该目录下面
		String fileUrl=getFileUrl(config.get("ProjectUrl")+config.get("CoreUrl"),tableName);
		
		//获取表注释  如果表注释最后一个字有表字那么去除这个字
		tableComment=getTableComment(tableName);
		
		String javaClassName=getJavaClassName(tableName)+"Info";
		// 获取文件下的定义的包名
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("package ").append(getPackName(fileUrl) + ";").append("\r\n\n");
		
		// 导入jar包
		if (tableInfo != null) {
			boolean flag = true;
			for (Map<String, Object> map : tableInfo) {
				String javaType = getJavaType((Integer) map.get("dataType"));
				if ("Date".equals(javaType)) {
					if (stringBuffer.toString().indexOf("import java.util.Date;") < 0) {
						flag = false;
						stringBuffer.append("import java.util.Date;").append("\r\n");
					}
				}else if ("BigDecimal".equals(javaType)) {
					if (stringBuffer.toString().indexOf("import java.math.BigDecimal;") < 0) {
						flag = false;
						stringBuffer.append("import java.math.BigDecimal;").append("\r\n");
					}
				}
			}
//			stringBuffer.append("import io.swagger.annotations.ApiModel;\r\n" + 
//					"import io.swagger.annotations.ApiModelProperty;\r\n");
			if (!flag) {
				stringBuffer.append("\n");
			}
		}
		stringBuffer.append("/**\r\n" + 
				" * "+tableComment+"Bean类 \r\n" + 
				" * @author "+config.get("ProgramName")+"\r\n" + 
				" */\r\n");
//		stringBuffer.append("@ApiModel(value=\""+tableComment+"对象模型\")\r\n");
		//拼接前面的类定义
        appendClassDefine(stringBuffer,javaClassName);

		if (tableInfo != null) {
			for (Map<String, Object> map : tableInfo) {
				String fieldName = getFileName((String) map.get("columnName"));
				String javaType = getJavaType((Integer) map.get("dataType"));
				stringBuffer.append("    // ").append(map.get("remarks")).append("\r\n");
//				stringBuffer.append("    @ApiModelProperty(value=\""+map.get("remarks")+"\")\r\n");
				stringBuffer.append("    private ").append(javaType).append(" ").append(fieldName).append(";")
						.append("\r\n");
				stringBuffer.append("\r\n");
			}

			for (Map<String, Object> map : tableInfo) {
				String fieldName = getFileName((String) map.get("columnName"));
				String javaType = getJavaType((Integer) map.get("dataType"));
				stringBuffer.append("    public ").append(javaType).append(" get").append(Utils.firstUpperCase(fieldName))
						.append("()").append("\r\n");
				stringBuffer.append("    {").append("\r\n");
				stringBuffer.append("        return ").append(fieldName).append(";").append("\r\n");
				stringBuffer.append("    }").append("\r\n");
				stringBuffer.append("\r\n");
				stringBuffer.append("    public void set").append(Utils.firstUpperCase(fieldName)).append("(").append(javaType)
						.append(" ").append(fieldName).append(")").append("\r\n");
				stringBuffer.append("    {").append("\r\n");
				stringBuffer.append("        this.").append(fieldName).append(" = ").append(fieldName).append(";")
						.append("\r\n");
				stringBuffer.append("    }").append("\r\n");

				stringBuffer.append("\r\n");

			}

			stringBuffer.append("\r\n");
		}

		stringBuffer.append("}\r\n");
		stringBuffer.append("//");
		
		return buildTargetFile(stringBuffer.toString(),fileUrl+javaClassName,"java");
	}

	//创建bean文件
	private boolean buildBeanFile(String tableName,String tableComment, List<Map<String, Object>> tableInfo, BuildType type, String mainTable) {
		//如果在目录当中已经有表名一样的目录，那么就放在该目录下面
		String fileUrl=getFileUrl(config.get("ProjectUrl")+config.get("BeanUrl"),tableName);
		//获取表注释  如果表注释最后一个字有表字那么去除这个字
		tableComment=getTableComment(tableName);
		String javaClassName=getJavaClassName(tableName)+"Display";
		// 获取文件下的定义的包名
		StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("package ").append(getPackName(fileUrl) + ";").append("\r\n\n");
		// 导入jar包
        stringBuffer.append(getBeanJar());
        // 拼接注释
        stringBuffer.append("/**\r\n" + 
				" * "+tableComment+"Display类 \r\n" + 
				" * @author "+config.get("ProgramName")+"\r\n" + 
				" */\r\n");
        //拼接前面的类定义
        appendClassDefine(stringBuffer,javaClassName);
        stringBuffer.append("	 private static Logger logger = Logger.getLogger("+javaClassName+".class);\r\n");
		//拼接方法
        stringBuffer.append("	 public static void process(HttpServletRequest request, Writer writer, HttpServletResponse response)\r\n" + 
        		"			throws IOException, ServletException {\r\n" + 
        		"		//获取前台传递参数\r\n" + 
        		"		String findKey=ChinaEncoder.GetUTF8CharsByDefault(request.getParameter(\"findKey\"));\r\n" + 
        		"		//获取当前页数\r\n" + 
        		"		String pages = request.getParameter(\"indexofpage\");\r\n" + 
        		"		int pagesInt=Integer.parseInt(pages);\r\n" + 
        		"		int currentPage=pages!=null?pagesInt<1?1:pagesInt:1;\r\n" + 
        		"		//拼接分页参数条件\r\n" + 
        		"		String pageParamCondition=appendPageParamCondition(...);\r\n" + 
        		"		//拼接查询条件\r\n" + 
        		"		String condition=appendQueryCondition(...);\r\n" + 
        		"		//拼接查询值\r\n" + 
        		"		Object[] params=appendQueryValue();\r\n" + 
        		"		//拼接详情sql\r\n" + 
        		"		String infoSql=appendInfoSQL(condition);\r\n" + 
        		"		//拼接总数sql\r\n" + 
        		"		String numSql=appendNumSql(condition);\r\n" + 
        		"		\r\n" + 
        		"		QueryPage queryPage = new QueryPage();\r\n" + 
        		"		ResultSet set = queryPage.getCarQuerySet(numSql, params, infoSql, params,\r\n" + 
        		"				Constant.NUMBER_USER_LIST_PAGE_ITEMS, currentPage);\r\n" + 
        		"		//拼接结果给前台\r\n" + 
        		"		responseResult(set,queryPage,writer,currentPage,pageParamCondition);\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接结果给前台\r\n" + 
        		"	 * @param set   查询结果\r\n" + 
        		"	 * @param queryPage 查询对象\r\n" + 
        		"	 * @param writer  流对象\r\n" + 
        		"	 * @param currentPage  当前页\r\n" + 
        		"	 * @param pageParamCondition  分页条件\r\n" + 
        		"	 */\r\n" + 
        		"	private static void responseResult(ResultSet set, QueryPage queryPage, Writer writer, int currentPage,\r\n" + 
        		"			String pageParamCondition) {\r\n" + 
        		"		int NumberOfRecord = queryPage.NumberOfRecord;\r\n" + 
        		"		int NumberOfPages = queryPage.NumberOfPages;\r\n" + 
        		"		PrintWriter pw = new PrintWriter(writer);\r\n" + 
        		"		pw.println(\"<script>tableHeader();\");\r\n" + 
        		"		try {\r\n" + 
        		"			while (null!=set&&set.next()) {\r\n" + 
        		"				pw.println();\r\n" + 
        		"			}\r\n" + 
        		"		}catch(Exception e) {\r\n" + 
        		"			logger.error(e.getMessage());\r\n" + 
        		"		}finally {\r\n" + 
        		"			queryPage.Close();\r\n" + 
        		"		}\r\n" + 
        		"		pw.println(\"closeTable();</script>\");\r\n" + 
        		"		PagingItems.WriteNavTable(pageParamCondition, NumberOfRecord, NumberOfPages, currentPage, pw);\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接分页参数条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendPageParamCondition() {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接查询值\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static Object[] appendQueryValue() {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接查询条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendQueryCondition(...) {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接总数sql\r\n" + 
        		"	 * @param condition 查询条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendNumSql(String condition) {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接详情sql\r\n" + 
        		"	 * @param condition 查询条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendInfoSQL(String condition) {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n"+ 
        		"");
        stringBuffer.append("}\r\n");
		stringBuffer.append("//");
		return buildTargetFile(stringBuffer.toString(),fileUrl+javaClassName,"java");
	}
	
	private boolean buildTargetFile(String fileStr,String fileUrl,String fileSuffix){
		// 创建文件
		File a = new File(fileUrl + "."+fileSuffix);
		if(a.exists()) {
			a= new File(fileUrl + "_1."+fileSuffix);
		}
		Utils.mkDirs(a);
		try {
			FileOutputStream fops = new FileOutputStream(a);
			fops.write(fileStr.getBytes());
			fops.flush();
			fops.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	private String getJavaClassName(String tableName) {
		String[] valueClassNameS=tableName.substring(4).split("_");
		return Arrays.stream(valueClassNameS).map(s->Utils.firstUpperCase(s)).reduce((s,b)->s+b).get();
	}
	private String getPackName(String fileUrl) {
		String result = "";
		if (!Utils.isEmpty(fileUrl)) {
			int index = fileUrl.indexOf("src");
			result = fileUrl.substring(index + 4, fileUrl.length());
			result = result.replaceAll("\\\\", ".");
			result = result.substring(0, result.length()-1);
		}
		return result;
	}
	
	/**
	 * 将数据库列类型转换为java数据类型
	 * 
	 * @param dataType
	 *            列类型
	 * @return String java数据类型
	 */
	private static String getJavaType(int dataType) {
		String javaType = "";
		if (dataType == Types.INTEGER) {
			javaType = "Integer";
		} else if (dataType == Types.BIGINT) {
			javaType = "Long";
		} else if (dataType == Types.CHAR || dataType == Types.VARCHAR || dataType == Types.NVARCHAR
				|| dataType == Types.CLOB||dataType == Types.BLOB) {
			javaType = "String";
		} else if (dataType == Types.TINYINT) {
			javaType = "Short";
		} else if (dataType == Types.FLOAT) {
			javaType = "float";
		} else if (dataType == Types.NUMERIC || dataType == Types.DECIMAL || dataType == Types.DOUBLE) {
			javaType = "BigDecimal";
		} else if (dataType == Types.DATE || dataType == Types.TIMESTAMP||dataType == Types.TIME) {
			javaType = "String";
		}
		return javaType;
	}
	
	/**
	 * 把以_分隔的列明转化为字段名
	 * @param columnName 列名
	 * @return String 字段名
	 */
	private static String getFileName(String columnName) {
		if (columnName == null) {
			return "";
		}

		StringBuffer fieldNameBuffer = new StringBuffer();

		boolean nextUpperCase = false;
		for (int i = 0; i < columnName.length(); i++) {
			char c = columnName.charAt(i);

			if (nextUpperCase) {
				fieldNameBuffer.append(columnName.substring(i, i + 1).toUpperCase());
			} else {
				fieldNameBuffer.append(c);
			}

			if (c == '_') {
				nextUpperCase = true;
			} else {
				nextUpperCase = false;
			}
		}

		String fieldName = fieldNameBuffer.toString();
		fieldName = fieldName.replaceAll("_", "");
		return fieldName;
	}
	
	private String getFileUrl(String fileUrl,String tableName) {
		String parentFile=Utils.getFileInExistFile(fileUrl,tableName);
		String parentFileReal=Utils.isEmpty(parentFile)?"":"\\"+parentFile;
		return fileUrl=fileUrl+parentFileReal;
	}
	
	private String getTableComment(String tableComment) {
		if(!Utils.isEmpty(tableComment)&&"表".equals(tableComment.substring(tableComment.length()-1))){
			return tableComment=tableComment.substring(0,tableComment.length()-1);
		}
		return "";
	}
	
	private String getBeanJar() {
		return "import java.io.IOException;\r\n" + 
				"import java.io.PrintWriter;\r\n" + 
				"import java.io.Writer;\r\n" + 
				"import java.net.URLEncoder;\r\n" + 
				"import java.sql.Connection;\r\n" + 
				"import java.sql.PreparedStatement;\r\n" + 
				"import java.sql.ResultSet;\r\n" + 
				"import java.text.ParseException;\r\n" + 
				"import java.util.ArrayList;\r\n" + 
				"import java.util.List;\r\n" + 
				"import javax.servlet.ServletException;\r\n" + 
				"import javax.servlet.http.HttpServletRequest;\r\n" + 
				"import javax.servlet.http.HttpServletResponse;\r\n" + 
				"import org.apache.log4j.Logger;\r\n" + 
				"import com.corget.util.ChinaEncoder;\r\n" + 
				"import com.corget.util.CommonUtil;\r\n" + 
				"import com.corget.util.CommonUtil.DataSourceType;\r\n" + 
				"import com.corget.util.CoreUtilDate;\r\n" + 
				"import jxl.write.Label;\r\n" + 
				"import jxl.write.WritableSheet;\r\n" + 
				"import ptt.Constant;\r\n" + 
				"import ptt.PagingItems;\r\n" + 
				"import ptt.runtime.DBEngine;\r\n" + 
				"import ptt.server.webserver;\r\n" + 
				"import ptt.store.DataBase;\r\n" + 
				"import ptt.store.QueryPage;\r\n\r\n";
	}
	
	private void appendClassDefine(StringBuffer stringBuffer,String javaClassName) {
		stringBuffer.append("public class ").append(javaClassName).append("\r\n");
		stringBuffer.append("{").append("\r\n");
	}
	
	private String getInsertSql(String tableName,List<Map<String, Object>> tableInfo) {
		StringBuffer stringBuffer=new StringBuffer();
		stringBuffer.append("insert into ").append(tableName).append(" ( ");
		int a=0;
		for (Map<String, Object> map : tableInfo) {
			String columnName=(String) map.get("columnName");
			if(a==tableInfo.size()-1) {
				stringBuffer.append(columnName).append(" ) value ( ");
			}else{
				stringBuffer.append(columnName).append(",");
			}
			a++;
		}
		a=0;
		for (Map<String, Object> map : tableInfo) {
			if(a==tableInfo.size()-1) {
				stringBuffer.append(" ?)");
			}else {
			    stringBuffer.append("?,");
			}
			a++;
		}
		return stringBuffer.toString();
	}
	private String getUpdateSql(String tableName,List<Map<String, Object>> tableInfo) {
		StringBuffer stringBuffer=new StringBuffer();
		stringBuffer.append("update ").append(tableName).append(" set ");
		List<String> keys=DataSourceInfoUtil.getTabelPrimaryKeys(tableName);
		int a=0;
		for (Map<String, Object> map : tableInfo) {
			String columnName=(String) map.get("columnName");
			if(a==tableInfo.size()-1) {
				stringBuffer.append(columnName).append("=? where ").append(keys.stream().map(s->s+"=?").reduce((s,b)->s+" and "+b).get());
			}else{
				stringBuffer.append(columnName).append("=?,");
			}
			a++;
		}
		return stringBuffer.toString();
	}
	private String getDeleteSql(String tableName) {
		StringBuffer stringBuffer=new StringBuffer();
		stringBuffer.append("delete from ").append(tableName).append(" where ");
		List<String> keys=DataSourceInfoUtil.getTabelPrimaryKeys(tableName);
		stringBuffer.append(keys.stream().map(s->s+"=?").reduce((s,b)->s+" and "+b).get());
		return stringBuffer.toString();
	}
	private String getSimpleQuerySql(String tableName) {
		StringBuffer stringBuffer=new StringBuffer();
		stringBuffer.append("select 1 from ").append(tableName).append(" where ");
		List<String> keys=DataSourceInfoUtil.getTabelPrimaryKeys(tableName);
		stringBuffer.append(keys.stream().map(s->s+"=?").reduce((s,b)->s+" and "+b).get());
		return stringBuffer.toString();
	}
	
	private void appendJspJs(StringBuffer stringBuffer,String javaClassName,String tableName,List<Map<String,Object>> tableInfo,String tableComment) {
		stringBuffer.append("<script type=\"text/javascript\" >\r\n");
		stringBuffer.append(getJspHead(tableName, tableInfo));
		stringBuffer.append(getJspUd(javaClassName, tableName, tableInfo));
		stringBuffer.append("function CloseTable()\r\n" + 
				"{\r\n" + 
				"	var html=\"\";\r\n" + 
				"	html+=\"</table>\";\r\n" + 
				"	return html;\r\n" + 
				"}\r\n");
		if(!config.containsKey("NoOperatingArea"))
		appendJspSelectAllAndDelete(stringBuffer, javaClassName, tableComment);
		if(!config.containsKey("NoOperatingArea"))
		appendJspAddEditLoad(stringBuffer, javaClassName, tableName, tableComment, tableInfo);;
		appendJspListMethonCode(stringBuffer, javaClassName, tableName, tableComment, tableInfo);
		stringBuffer.append("</script>\r\n" + 
				"</head>\r\n");
	}
	
	private void appendJspHtmLHeadAndStype(StringBuffer stringBuffer) {
		stringBuffer.append("<html>\r\n" + 
				"<head>\r\n" + 
				"<jsp:include page=\"common.jsp\" flush=\"true\" />\r\n" + 
				"<style type=\"text/css\">\r\n" + 
				".col5{\r\n" + 
				"    width : 5%;\r\n" + 
				"    font-size : 9pt;\r\n" + 
				"}\r\n" + 
				".col7{\r\n" + 
				"    width : 7%;\r\n" + 
				"    font-size : 9pt;\r\n" + 
				"}\r\n" + 
				".col10{\r\n" + 
				"    width : 10%;\r\n" + 
				"    font-size : 9pt;\r\n" + 
				"}\r\n" + 
				".zaiinline{\r\n" + 
				"  width: 83.33333333%;\r\n" + 
				"  display:inline;\r\n" + 
				"}\r\n" + 
				".widthset{\r\n" + 
				"width: 41.66666667%;\r\n" + 
				"}\r\n" + 
				"#insertDiv input:focus{\r\n" + 
				"   border-color:1px red;\r\n" + 
				"}\r\n" + 
				"#insertDiv input:unfocus{\r\n" + 
				"   border-color:#ccc;\r\n" + 
				"}\r\n" + 
				"</style>");
	}
	
	private void appendJspImportPackageAndTop(StringBuffer stringBuffer,String jspName,String javaClassName) {
		stringBuffer.append("<!-- \r\n" + 
				"        页面名:"+jspName+".jsp"+"\r\n" + 
				"        后台业务处理类名: "+javaClassName+"Handler"+"\r\n" + 
				"-->\r\n" + 
				"<%@page import=\"ptt.Constant\"%>\r\n" + 
				"<%@page import=\"ptt.server.webserver\"%>\r\n" + 
				"<%@page language=\"java\" contentType=\"text/html;charset=UTF-8\" %>\r\n" + 
				"<%@page import=\"com.corget.util.ChinaEncoder\" %>\r\n" + 
				"\r\n" + 
				"<%\r\n" + 
				"      //获取查找关键字\r\n" + 
				"	  String findKey=request.getParameter(\"findKey\")==null?\"\":request.getParameter(\"findKey\");\r\n" + 
				"	  findKey=ChinaEncoder.GetUTF8CharsByDefault(findKey);\r\n" + 
				"%>\r\n");
	}
	
	private void appendJspSelectAllAndDelete(StringBuffer stringBuffer,String javaClassName,String tableComment) {
		stringBuffer.append("\r\n/*批量删除多行数据  S*/\r\n" + 
				"function deleteDataS()\r\n" + 
				"{\r\n" + 
				"	var arrayId=new Array();\r\n" + 
				"	$(\"input:checkBox[name='"+Utils.firstUpperCase(javaClassName)+"']:checked\").each(function(){\r\n" + 
				"		arrayId.push($(this).val());\r\n" + 
				"	});\r\n" + 
				"	if(arrayId.length==0){\r\n" + 
				"		buildToastr(\"warning\",\"请选择要删除的"+tableComment+"!\")\r\n" + 
				"		return false;\r\n" + 
				"	}\r\n" + 
				"	delete"+javaClassName+"(arrayId.toString());\r\n" + 
				"}\r\n" + 
				"function delete"+javaClassName+"(idS){\r\n" + 
				"	Common.confirm({\r\n" + 
				"	      title: \"询问\",\r\n" + 
				"	      message: \"确定是否删除数据?\",\r\n" + 
				"	      operate: function (reselt) {\r\n" + 
				"	          if (reselt) {\r\n" + 
				"	        	  $.post(\"deleteDataUrl\", {\r\n" + 
				"						idS : idS,\r\n" + 
				"					}, function(jsondata) {\r\n" + 
				"						if(jsondata.code!=\"200\"||jsondata.code==\"\"||jsondata.code==undefined){\r\n" + 
				"							buildToastr(\"error\",jsondata.msg);\r\n" + 
				"							return false;\r\n" + 
				"						}\r\n" + 
				"						list"+javaClassName+"();\r\n" + 
				"					    buildToastr(\"success\",\"删除成功!\");\r\n" + 
				"					}, \"json\");\r\n" + 
				"	          } else {\r\n" + 
				"	        	  \r\n" + 
				"	          }\r\n" + 
				"	      }\r\n" + 
				"	  })\r\n" + 
				"}\r\n" + 
				"//全选\r\n" + 
				"function selectAllTd(thisObj){\r\n" + 
				"	var checkValue=$(thisObj).prop(\"checked\");\r\n" + 
				"	$(\"input:checkBox[name='"+javaClassName+"']\").each(function(){\r\n" + 
				"		$(this).prop(\"checked\",checkValue);\r\n" + 
				"	});\r\n" + 
				"}\r\n" + 
				"/*批量删除多行数据  E*/\r\n");
	}
	
	private void appendJspAddEditLoad(StringBuffer stringBuffer,String javaClassName,String tableName,String tableComment,List<Map<String,Object>> tableInfo) {
		String key=DataSourceInfoUtil.getTabelPrimaryKeys(tableName).stream().findFirst().get();
		//拼接显示 添加或者修改的框
		stringBuffer.append("var "+key+";\r\n" + 
				"function showAddOrEdit"+javaClassName+"Modal(id){\r\n" + 
				"	if(id!=\"\"){//编辑\r\n" + 
				"		"+key+"=id\r\n" + 
				"		//加载编辑"+tableComment+"数据  给addOrEdit"+javaClassName+"Modal 添加展示事件\r\n" + 
				"    	loadEdit"+javaClassName+"Data();\r\n" + 
				"		$(\"#myModalLabel\").html(\"编辑"+tableComment+"\");\r\n" + 
				"	}else{//增加\r\n" + 
				"		$(\"#myModalLabel\").html(\"添加"+tableComment+"\");\r\n" + 
				"		"+key+"=\"\";\r\n");
		tableInfo.stream().map(s->{return (String)s.get("columnName");}).forEach(s->{
			stringBuffer.append("		$(\"#"+getFileName(s)+"\").val(\"\");\r\n"); 
		});
		stringBuffer.append("	}\r\n" + 
				"	$(\"#addOrEdit"+javaClassName+"Modal div[name='divinput']\").removeClass(\"has-error\");\r\n" + 
				"	$(\"#addOrEdit"+javaClassName+"Modal\").modal(\"show\");\r\n" + 
				"}\r\n");
		
		stringBuffer.append("//添加或"+tableComment+"\r\n" + 
				"function addOrEdit"+javaClassName+"Modal(){\r\n");
		
		tableInfo.stream().map(m->{return getFileName((String)m.get("columnName"));}).forEach(s->{
			stringBuffer.append("	var "+s+"=$(\"#"+s+"\").val();\r\n");
		});
		tableInfo.stream().forEach(m->{
			String columnName=getFileName((String) m.get("columnName"));
			String remarks=(String) m.get("remarks");
			stringBuffer.append("	if("+columnName+"==\"\"){\r\n" + 
					"		buildToastr(\"warning\",\"请填写"+remarks+"!\");\r\n" + 
					"		$(\"#"+columnName+"\").focus();\r\n" + 
					"		$(\"#"+columnName+"\").parent().parent().addClass(\"has-error\");\r\n" + 
					"		return false;\r\n" + 
					"	}\r\n");
		});;
			
		stringBuffer.append("	var url=\"\";\r\n" + 
				"    var data={};\r\n" + 
				"	if("+key+"!=\"\"&&"+key+"!=null&&"+key+"!=undefined){//编辑\r\n" + 
				"		 data={\r\n");
		List<String> listColumn=tableInfo.stream().map(m->{return getFileName((String)m.get("columnName"));}).collect(Collectors.toList());
		int a=0;
		for (String columnName : listColumn) {
			if(a==listColumn.size()-1) {
				stringBuffer.append("				   "+columnName+":"+columnName+"\r\n");
			}else {
				stringBuffer.append("				   "+columnName+":"+columnName+",\r\n");
			}
			a++;
		}
		
		stringBuffer.append("				 };\r\n" + 
				"         url=updateDataUrl;\r\n" + 
				"	}else{//增加\r\n" + 
				"		data={\r\n");
		a=0;
		for (String columnName : tableInfo.stream().map(m->{return getFileName((String)m.get("columnName"));}).collect(Collectors.toList())) {
			if(a==listColumn.size()-1) {
				stringBuffer.append("				   "+columnName+":"+columnName+"\r\n");
			}else {
				stringBuffer.append("				   "+columnName+":"+columnName+",\r\n");
			}
			a++;
		}
		stringBuffer.append("				 };\r\n"); 
		stringBuffer.append("		url=insertDataUrl;\r\n"+
		        "	}\r\n" + 
				"	   $.post(url,data,function(jsondata){\r\n" + 
				"		   if(jsondata.code!=\"200\"||jsondata.code==\"\"||jsondata.code==undefined){\r\n" + 
				"				buildToastr(\"error\",jsondata.msg);\r\n" + 
				"				return false;\r\n" + 
				"			}\r\n" + 
				"		   buildToastr(\"success\",\"提交成功!\");\r\n" + 
				"		   $(\"#addOrEdit"+javaClassName+"Modal\").modal(\"hide\");\r\n" + 
				"		   /* location.reload(); */\r\n" + 
				"	   },\"json\");\r\n" + 
				"}");
		
		stringBuffer.append("//加载编辑数据\r\n" + 
				"function loadEdit"+javaClassName+"Data(){\r\n" + 
				"	if("+key+"!=\"\"&&"+key+"!=null&&"+key+"!=undefined){\r\n" + 
				"			//加载编辑数据\r\n" + 
				"			var url=get"+javaClassName+"Data;\r\n" + 
				"			var data={id:"+key+"};\r\n" + 
				"			$.post(url,data,function(jsondata){\r\n" + 
				"				if(jsondata.code==\"200\"){\r\n"+ 
				"					   var record=jsondata.data;\r\n");
		for (String columnName : tableInfo.stream().map(m->{return getFileName((String)m.get("columnName"));}).collect(Collectors.toList())) {
			stringBuffer.append("					    $(\"#"+columnName+"\").val(record."+columnName+");\r\n");
		}
		stringBuffer.append("				}\r\n" + 
				"			},\"json\");\r\n" + 
				"	}\r\n" + 
				"}\r\n" + 
				"\r\n" + 
				"function bindModalHide(){\r\n" + 
				"	$('#addOrEdit"+javaClassName+"Modal').on('hide.bs.modal', function () {\r\n" + 
				"		  list"+javaClassName+"();\r\n" + 
				"	})\r\n" + 
				"}");
	}
	
	private void appendJspBody(StringBuffer stringBuffer,String tableComment,String javaClassName,List<Map<String,Object>> tableInfo) {
		stringBuffer.append("<body>\r\n" + 
				"<span class=\"common_title_font\">"+tableComment+"管理-></span>\r\n" + 
				" <div class=\"common_center_rect\">\r\n" + 
				" <div style='background:#f5f5f5;border-radius:5px;' >\r\n" + 
				"<p style=\"padding-top:10px;\">\r\n" + 
				"<span style=\"margin-left:20%;\"></span>\r\n" + 
				"<input id=\"findKey\" type=\"text\" placeholder=\"  \"  class=\"form-control\" style=\"width:30%;display:inline;vertical-align: top;outline: none;box-shadow: none;\"  size=\"20\">\r\n" + 
				"<input  type=\"button\" value=\" 查  询 \" style=\"display:inline;vertical-align: top;outline: none;box-shadow: none;\" class=\"btn btn-primary\" onClick=\"javascript:list"+javaClassName+"();\">\r\n" + 
				"<br><br>\r\n" + 
				"<label class=\"text-info\" style=\"margin-left:20%;\">支持搜索:</label>\r\n" + 
				"</p>\r\n" + 
				"<p></p>\r\n" + 
				"<p style=\"padding-top:10px;padding-bottom:10px;\">&nbsp;&nbsp;&nbsp;操作区: <button class=\"btn btn-sm btn-info\" onclick=\"showAddOrEdit"+javaClassName+"Modal('')\">添加记录</button> &nbsp;&nbsp;<button class=\"btn btn-sm btn-danger\" onclick=\"deleteDataS()\">批量删除</button></p>\r\n" + 
				"</div>\r\n" + 
				"<hr>\r\n" + 
				"<div id=\"tableDiv\">\r\n" + 
				"</div>\r\n" + 
				"</div>\r\n" + 
				"\r\n");
		if(!config.containsKey("NoOperatingArea")) {
		stringBuffer.append("<!-- 模态框（Modal） -->\r\n" + 
				"<div class=\"modal fade\" id=\"addOrEdit"+javaClassName+"Modal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\r\n" + 
				"    <div class=\"modal-dialog\">\r\n" + 
				"        <div class=\"modal-content\">\r\n" + 
				"            <div class=\"modal-header\">\r\n" + 
				"                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\r\n" + 
				"                <h4 class=\"modal-title\" id=\"myModalLabel\"></h4>\r\n" + 
				"            </div>\r\n" + 
				"            <div class=\"modal-body\">\r\n" + 
				"                   <!-- disabled=\"true\" readonly 提示:此项目自动生成 -->\r\n" + 
				"			<p></p>\r\n" + 
				"			<div id=\"insertDiv\" style=\"position:relative;margin-left:20px;\">\r\n" + 
				"		       <div style=\"margin-left:15px;\">\r\n");
		tableInfo.stream().forEach(m->{
			String columnName=getFileName((String)m.get("columnName"));
			String remark=(String)m.get("remarks");
			stringBuffer.append("		       <div class=\"form-group\" name=\"divinput\">\r\n" + 
					"					<label class=\"widthset control-label zaiinline\"><span style=\"color:red;\">*</span>"+remark+"：</label>\r\n" + 
					"					<div class=\"zaiinline\">\r\n" + 
					"						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id=\""+columnName+"\" type=\"text\" placeholder=\""+remark+"\"\r\n" + 
					"								class=\"form-control\" style=\"width:30%;display:inline;\"><span id=\"errorMsg\" style=\"display:none\"></span>\r\n" + 
					"					</div>\r\n" + 
					"				</div>\r\n");
		});

		stringBuffer.append("				</div>\r\n" + 
				"				</div>\r\n" + 
				"            </div>\r\n" + 
				"            <div class=\"modal-footer\">\r\n" + 
				"                <button type=\"button\" class=\"btn btn-warning\" data-dismiss=\"modal\">关闭</button>\r\n" + 
				"                <button type=\"button\" class=\"btn btn-success\" onclick=\"addOrEditProductRepairRecordModal()\">提交</button>\r\n" + 
				"            </div>\r\n" + 
				"        </div><!-- /.modal-content -->\r\n" + 
				"    </div><!-- /.modal -->\r\n" + 
				"</div>\r\n" + 
				"\r\n" + 
				"\r\n" + 
				"\r\n" + 
				"\r\n" + 
				"<!-- confirm 组件  S-->\r\n" + 
				"<script type=\"text/javascript\">\r\n" + 
				"var Common = {\r\n" + 
				"	    confirm:function(params){\r\n" + 
				"	        var model = $(\"#common_confirm_model\");\r\n" + 
				"	        model.find(\".title\").html(params.title)\r\n" + 
				"	        model.find(\".message\").html(params.message)\r\n" + 
				"\r\n" + 
				"	        $(\"#common_confirm_btn\").click()\r\n" + 
				"	        //每次都将监听先关闭，防止多次监听发生，确保只有一次监听\r\n" + 
				"	        model.find(\".cancel\").off(\"click\")\r\n" + 
				"	        model.find(\".ok\").off(\"click\")\r\n" + 
				"\r\n" + 
				"	        model.find(\".ok\").on(\"click\",function(){\r\n" + 
				"	            params.operate(true)\r\n" + 
				"	        })\r\n" + 
				"\r\n" + 
				"	        model.find(\".cancel\").on(\"click\",function(){\r\n" + 
				"	            params.operate(false)\r\n" + 
				"	        })\r\n" + 
				"	    }\r\n" + 
				"	}\r\n" + 
				"</script>\r\n" + 
				"<input type=\"hidden\" id=\"common_confirm_btn\" class=\"btn btn-primary btn-lg\" data-toggle=\"modal\" data-target=\"#common_confirm_model\">\r\n" + 
				"<div id=\"common_confirm_model\" class=\"modal\">\r\n" + 
				"    <div class=\"modal-dialog modal-sm\">\r\n" + 
				"        <div class=\"modal-content\">\r\n" + 
				"            <div class=\"modal-header\">\r\n" + 
				"                <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\r\n" + 
				"                <h5 class=\"modal-title\"><i class=\"fa fa-exclamation-circle\"></i> <span class=\"title\"></span></h5>\r\n" + 
				"            </div>\r\n" + 
				"            <div class=\"modal-body small\">\r\n" + 
				"                <p ><span class=\"message\"></span></p>\r\n" + 
				"            </div>\r\n" + 
				"            <div class=\"modal-footer\" >\r\n" + 
				"                <button type=\"button\" class=\"btn btn-primary ok\" data-dismiss=\"modal\">确认</button>\r\n" + 
				"                <button type=\"button\" class=\"btn btn-default cancel\" data-dismiss=\"modal\">取消</button>\r\n" + 
				"            </div>\r\n" + 
				"        </div>\r\n" + 
				"    </div>\r\n" + 
				"</div>\r\n" + 
				"<!-- confirm 组件  E-->\r\n" + 
				"\r\n" + 
				"\r\n" + 
				"<div class=\"modal fade\" id=\"infoShowModel\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\r\n" + 
				"    <div class=\"modal-dialog\">\r\n" + 
				"        <div class=\"modal-content\">\r\n" + 
				"            <div class=\"modal-header\">\r\n" + 
				"                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\r\n" + 
				"                <h4 class=\"modal-title\" id=\"infoShowModelTitle\"></h4>\r\n" + 
				"            </div>\r\n" + 
				"            <div class=\"modal-body\"><textarea id=\"infoShowModelInfo\" style=\"resize:none;width:100%;padding:10px;\" rows=\"5\"></textarea></div>\r\n" + 
				"        </div><!-- /.modal-content -->\r\n" + 
				"    </div><!-- /.modal -->\r\n" + 
				"</div>\r\n" + 
				"\r\n");
		}
		stringBuffer.append("</body>\r\n" + 
				"</html>");
	}
	
	private void appendJspListMethonCode(StringBuffer stringBuffer,String javaClassName,String tableName,String tableComment,List<Map<String,Object>> tableInfo) {
		String key=DataSourceInfoUtil.getTabelPrimaryKeys(tableName).stream().findFirst().get();
		List<String> columnList=tableInfo.stream().map(s->{return getFileName((String)s.get("columnName"));}).collect(Collectors.toList());
		int a=0;
		StringBuffer udParamStringBuffer=new StringBuffer();
		for (String column : columnList) {
			if(a==columnList.size()-1) {
				udParamStringBuffer.append("row."+column);
			}else {
				udParamStringBuffer.append("row."+column+",");
			}
			a++;
		}
		String udParam=udParamStringBuffer.toString();
		udParamStringBuffer.setLength(0);
        a=0;
		for (String column : columnList) {
			if(a==columnList.size()-1) {
				udParamStringBuffer.append("\""+column+"\"");
			}else {
				udParamStringBuffer.append("\""+column+"\",");
			}
			a++;
		}
        String jsonParam=udParamStringBuffer.toString();

		stringBuffer.append("function list"+javaClassName+"(param){\r\n" + 
				"	$(\"#tableDiv\").html(\"\");\r\n" + 
				"	var html=\"\";\r\n" + 
				"	html+=TableHeader();\r\n" + 
				"	var findKey=$(\"#findKey\").val();\r\n" + 
				"	var paramdata={findKey:findKey,\r\n" + 
				"			"+key+":"+key+",\r\n" + 
				"    		indexOfPage:1,\r\n" + 
				"    		pageCount:20,\r\n" + 
				"    		};\r\n" + 
				"	$.post(listDataUrl,paramdata,function(jsondata){\r\n" + 
				"		if(jsondata.code==\"200\"){\r\n" + 
				"			$.each(jsondata.data,function(i,row){\r\n" + 
				"				html+=Ud("+udParam+");\r\n" + 
				"			});\r\n" + 
				"			html+=CloseTable();\r\n" + 
				"			paramdataStr=JSON.stringify(paramdata);\r\n" + 
				"			var jsonvalueStr=["+jsonParam+"];\r\n" + 
				"			var functionStrs=[\"TableHeader\",\"Ud\",\"CloseTable\"];\r\n" + 
				"			html+=GetHtmlNavTable(url,jsondata.dataCount,jsondata.pages,jsondata.currentPage,paramdataStr,jsonvalueStr,functionStrs,\"tableDiv\");\r\n" + 
				"			$(\"#tableDiv\").html(html);\r\n" + 
				"		}else{\r\n" + 
				"			buildToastr(\"error\",jsondata.msg);\r\n" + 
				"		}\r\n" + 
				"	},\"json\");\r\n" + 
				"}");
	}
	
	private void appendQueryCode(StringBuffer stringBuffer) {
		//拼接方法
        stringBuffer.append("\r\n	 public static void process(HttpServletRequest request,HttpServletResponse response)\r\n" + 
        		"			throws IOException, ServletException {\r\n" + 
        		"		//获取前台传递参数\r\n" + 
        		"		String findKey=ChinaEncoder.GetUTF8CharsByDefault(request.getParameter(\"findKey\"));\r\n" + 
        		"		//获取当前页数\r\n" + 
        		"		String pages = request.getParameter(\"indexofpage\");\r\n" + 
        		"		int pagesInt=Integer.parseInt(pages);\r\n" + 
        		"		int currentPage=pages!=null?pagesInt<1?1:pagesInt:1;\r\n" + 
        		"		//拼接分页参数条件\r\n" + 
        		"		String pageParamCondition=appendPageParamCondition(...);\r\n" + 
        		"		//拼接查询条件\r\n" + 
        		"		String condition=appendQueryCondition(...);\r\n" + 
        		"		//拼接查询值\r\n" + 
        		"		Object[] params=appendQueryValue();\r\n" + 
        		"		//拼接详情sql\r\n" + 
        		"		String infoSql=appendInfoSQL(condition);\r\n" + 
        		"		//拼接总数sql\r\n" + 
        		"		String numSql=appendNumSql(condition);\r\n" + 
        		"		\r\n" + 
        		"		QueryPage queryPage = new QueryPage();\r\n" + 
        		"		ResultSet set = queryPage.getCarQuerySet(numSql, params, infoSql, params,\r\n" + 
        		"				Constant.NUMBER_USER_LIST_PAGE_ITEMS, currentPage);\r\n" + 
        		"		//拼接结果给前台\r\n" + 
        		"		responseResult(set,queryPage,writer,currentPage,pageParamCondition);\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接结果给前台\r\n" + 
        		"	 * @param set   查询结果\r\n" + 
        		"	 * @param queryPage 查询对象\r\n" + 
        		"	 * @param writer  流对象\r\n" + 
        		"	 * @param currentPage  当前页\r\n" + 
        		"	 * @param pageParamCondition  分页条件\r\n" + 
        		"	 */\r\n" + 
        		"	private static void responseResult(ResultSet set, QueryPage queryPage, Writer writer, int currentPage,\r\n" + 
        		"			String pageParamCondition) {\r\n" + 
        		"		int NumberOfRecord = queryPage.NumberOfRecord;\r\n" + 
        		"		int NumberOfPages = queryPage.NumberOfPages;\r\n" + 
        		"		try {\r\n" + 
        		"			while (null!=set&&set.next()) {\r\n" + 
        		"			}\r\n" + 
        		"		}catch(Exception e) {\r\n" + 
        		"			logger.error(e.getMessage());\r\n" + 
        		"		}finally {\r\n" + 
        		"			queryPage.Close();\r\n" + 
        		"		}\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接分页参数条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendPageParamCondition() {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接查询值\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static Object[] appendQueryValue() {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接查询条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendQueryCondition(...) {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接总数sql\r\n" + 
        		"	 * @param condition 查询条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendNumSql(String condition) {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n" + 
        		"\r\n" + 
        		"	/**\r\n" + 
        		"	 * 拼接详情sql\r\n" + 
        		"	 * @param condition 查询条件\r\n" + 
        		"	 * @return\r\n" + 
        		"	 */\r\n" + 
        		"	private static String appendInfoSQL(String condition) {\r\n" + 
        		"		return null;\r\n" + 
        		"	}\r\n"+ 
        		"");
	}
	
	private String getJspHead(String tableName,List<Map<String, Object>> tableInfo) {
		StringBuffer stringBuffer=new StringBuffer();
		boolean foreignLanguageRequired=config.containsKey("ForeignLanguageRequired");
		stringBuffer.append("function TableHeader()\r\n" + 
				"{    \r\n" + 
				"	 var html=\"\";\r\n" + 
				"    html+=\"<table width=125%  class='table table-bordered' >\";\r\n" + 
				"    html+=\"<tr bgcolor='#CFCFCF'>\";\r\n");
		
		if(!config.containsKey("NoOperatingArea")) {
		    if(foreignLanguageRequired)
			stringBuffer.append("    html+=\"<td class='col5' align='center'><input class='checkbox' style='display:inline;' type='checkbox' onClick='selectAllTd(this);'><span data-i18n-text='SelectAll'></span></td>\";\r\n");
		    stringBuffer.append("    html+=\"<td class='col5' align='center'><input class='checkbox' style='display:inline;' type='checkbox' onClick='selectAllTd(this);'>全选</td>\";\r\n");
		   //操作区域
		    if(foreignLanguageRequired)
			stringBuffer.append("    html+=\"<td class='col7' align='center'><span data-i18n-text='Operate'></span></td>\";\r\n");
		    stringBuffer.append("    html+=\"<td class='col7' align='center'>操作</td>\";\r\n");
		}
		
		tableInfo.forEach(s->{
		    String remarks=(String) s.get("remarks");
		    String columnName=(String) s.get("columnName");
		    if(!foreignLanguageRequired)
			stringBuffer.append("    html+=\"<td class='col5' align='center'>"+remarks+"</td>\";\r\n");
			stringBuffer.append("    html+=\"<td class='col5' align='center'><span data-i18n-text='"+columnName+"'></span></td>\";\r\n");
		});
		stringBuffer.append("	html+=\"</tr>\";\r\n" + 
				"	return html;\r\n" + 
				"}\r\n" + 
				"");
		return stringBuffer.toString();
	}
	
	private String getJspUd(String className,String tableName,List<Map<String, Object>> tableInfo) {
		StringBuffer stringBuffer=new StringBuffer();
		List<String> keys=DataSourceInfoUtil.getTabelPrimaryKeys(tableName);
        String key=keys.stream().findFirst().get();
        Stream<String> streamColumn=tableInfo.stream().map(s->{return getFileName((String)(String)s.get("columnName"));});
        String upParam=streamColumn.reduce((s,b)->s+","+b).get();
		stringBuffer.append("function Ud("+upParam+"){\r\n" + 
				"	var html=\"\";\r\n" + 
				"	html+=\"<tr>\";\r\n");
		if(!config.containsKey("NoOperatingArea")) {
		stringBuffer.append("	html+=\"<td class='col5' align='center'><input type='checkbox' name='"+Utils.firstUpperCase(className)+"' value='\"+id+\"'></td>\";\r\n");
		stringBuffer.append("	html+=\"<td class='col7' align='center'>\";\r\n" + 
				"	html+=\"<button class='btn btn-xs btn-warning' onclick='showAddOrEdit"+className+"(\\\"\"+"+key+"+\"\\\")'>修改</button>\";\r\n" + 
				"	html+=\"&nbsp;\";\r\n" + 
				"	html+=\"<button class='btn btn-xs btn-danger' onclick='delete"+className+"(\\\"\"+"+key+"+\"\\\")'>删除</button>\";\r\n" + 
				"	html+=\"</td>\";\r\n");
		}
		tableInfo.stream().map(s->{return getFileName((String)(String)s.get("columnName"));}).forEach(columnName->{
			stringBuffer.append("    html+=\"<td class='col5' align='center'>\"+"+getFileName(columnName)+"+\"</td>\";\r\n");	
		});
		stringBuffer.append("	html+=\"</tr>\";\r\n" + 
				"	return html;\r\n"
				+ "}");
		return stringBuffer.toString();
	}
	//创建类型
	public enum BuildType{
		MAINTABLE,//有主表
		NOMAINTABLE;//没有主表
	};
}
//                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 